﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HCSExtensions;
using System.Data.Objects.DataClasses;
using DAL;
using HCSExtensions.Enums;
using System.Data.Objects;

namespace BLL
{
    public class BaseProvider
    {
        internal KFEntities Context;

        public BaseProvider()
        {
            this.Context = new KFEntities();
        }

        public virtual TransactionEvent Add(EntityObject entity)
        {
            TransactionEvent transaction = new TransactionEvent();
            try
            {
                this.Context.AddObject(BaseExtensions.GetEntitySetFullName(this.Context, entity.GetType().Name), entity);
                this.Context.SaveChanges();
                transaction.ReturnObject = entity;
            }
            catch (Exception ex)
            {
                transaction.Exception = ex;
                return transaction;
            }

            return transaction;
        }

        public virtual TransactionEvent Update(EntityObject entity)
        {
            TransactionEvent transaction = new TransactionEvent();
            try
            {
                //this.Context.Attach(entity);
                //this.Context.AttachTo(BaseExtensions.GetEntitySetFullName(this.Context, entity.GetType().Name), entity);
                //entity.SetAllModified<EntityObject>(this.Context);
                this.Context.SaveChanges();
            }
            catch (Exception ex)
            {
                transaction.Exception = ex;
                return transaction;
            }

            transaction.ReturnObject = entity;
            return transaction;
        }

        public virtual TransactionEvent Delete(EntityObject entity)
        {
            TransactionEvent transaction = new TransactionEvent();
            try
            {
                this.Context.DeleteObject(entity);
                this.Context.SaveChanges();
            }
            catch (Exception ex)
            {
                transaction.Exception = ex;
                return transaction;
            }

            return transaction;
        }
    }
}
